package com.seven.smartsnmp.handler;

import com.seven.smartsnmp.base.MyException;
import com.seven.smartsnmp.snmp.SNMPFactory;
import com.seven.smartsnmp.utils.SNMPUtils;
import net.percederberg.mibble.MibValueSymbol;
import net.percederberg.mibble.snmp.SnmpObjectType;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;

import java.util.Vector;

/**
 * 更新操作
 */

/**
 * @author Admin
 */
public class UpdateHandler {

    public  void update(Object object, Snmp snmp, Target target) throws MyException {
        try {
            String oid = SNMPUtils.getMibOIDofClass(object.getClass());
            MibValueSymbol mibValueSymbol = SNMPFactory.getInstance().getMibSymbolByOid(oid);
            String indexOID = SNMPUtils.getTableOrGroupIndexOID(object, mibValueSymbol);
            Class clazz = object.getClass();
            Vector vector = SNMPUtils.getWritedFieldsInMibNode(clazz, mibValueSymbol);
            PDU pdu = SNMPUtils.createPdu(target.getVersion());
            for(int i = 0; i < vector.size(); i++) {
                MibValueSymbol symbol = (MibValueSymbol)vector.get(i);
                String OID = symbol.getValue().toString();
                String nodeOID = OID + "." + indexOID;
                String oidName = mibValueSymbol.getMib().getSymbolByOid(OID).getName();
                SnmpObjectType snmpObjectType = (SnmpObjectType)symbol.getType();
                Variable var15 = SNMPUtils.getFieldValue(object, oidName, snmpObjectType.getSyntax());
                pdu.add(new VariableBinding(new OID(nodeOID), (Variable)var15));
            }
            ResponseEvent event = snmp.set(pdu, target);
            SNMPUtils.checkSNMPErro(event);
        } catch (Exception e) {
            String msg = "把对象数据写入到设备snmp中出错,对象:" + object.getClass().getName() + ",设备ip:" + target.getAddress() + ",错误:"+ e.getMessage();
            throw new MyException(msg);
        }
    }
}
